package com.example.testapp.activity.activity.study;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.testapp.R;
import com.example.testapp.activity.activity.BaseActivity;
import com.example.testapp.activity.http.AsyncHttpUtil;
import com.example.testapp.activity.http.Contacts;
import com.example.testapp.activity.model.ArticleComment;
import com.example.testapp.activity.model.PhonePaging;
import com.example.testapp.activity.util.CircleImageView;
import com.example.testapp.activity.util.JsonUtils;
import com.example.testapp.activity.util.MD5Utils;
import com.example.testapp.activity.view.ErrorHintView;
import com.example.testapp.activity.view.listview.PullToRefreshAdapterViewBase;
import com.example.testapp.activity.view.listview.PullToRefreshBase;
import com.example.testapp.activity.view.listview.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by l on 2016/9/27.
 */

public class PhoneTechCommentActivity extends BaseActivity {

    private PullToRefreshListView  mListView;
    private ErrorHintView   mErrorHintView;

    private List<ArticleComment>  ArticleData = new ArrayList<ArticleComment>();
    private TechCommentAdapter   mAdapter;

    private int  offset = 0;            //第N条数据
    private boolean  isPage = true;       //是否还有下一页
    private LinearLayout  footerView;  //最后一条listview
    private String docid;

    public static int VIEW_LIST = 1;
    /**显示断网**/
    public static int VIEW_WIFIFAILUER = 2;
    /** 显示加载数据失败 **/
    public static int VIEW_LOADFAILURE = 3;
    public static int VIEW_LOADING = 4;
    public static int VIEW_NODATA = 5;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_comment);
        getWindow().setBackgroundDrawable(null);

        initLayout();
    }

    private void initLayout() {
        Intent intent = getIntent();
        docid = intent.getStringExtra("docid");

        RelativeLayout headView = (RelativeLayout) this.findViewById(R.id.head);
        headView.findViewById(R.id.back_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        TextView  mTitle = (TextView) headView.findViewById(R.id.head_title);
        mTitle.setText("更多评论");
        mListView = (PullToRefreshListView)this.findViewById(R.id.list);
        mErrorHintView = (ErrorHintView)this.findViewById(R.id.hintView);

        setUpPullToList();
        showLoading(VIEW_LOADING);
        loadPhoneTechComments(true);
    }

    /**
     * 设置listview的下拉刷新
     */
    private void setUpPullToList() {
         mAdapter = new TechCommentAdapter(ArticleData, mContext);
         mListView.setAdapter(mAdapter);

        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (refreshView.isHeaderShown()){
                    defParams();
                    showLoading(VIEW_LOADING);
                    loadPhoneTechComments(true);
                }
            }
        });

        mListView.setOnPreRefreshingAnimListener(new PullToRefreshAdapterViewBase.OnPreRefreshingAnimListener() {
            @Override
            public void onPreRefreshingAnim() {
                mListView.setFooterLoadingViewHeaderText("加载更多评论");
            }
        });

        mListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (isPage){
                    //滑动到底部自动刷新
                    loadPhoneTechComments(false);
                }else {
                    //没有下一页了
                    mListView.onRefreshComplete();
                    if (footerView == null){
                        footerView = (LinearLayout)View.inflate(mContext, R.layout.item_pull_to_refresh_footer, null);
                        TextView footer = (TextView)footerView.findViewById(R.id.footer);
                        footer.setText("到底了呢 - 共" + ArticleData.size() + "条评论");
                        mListView.getRefreshableView().addFooterView(footerView);
                    }
                }
            }
        });
    }

    /**
     * 显示动态加载的view
     *
     * @param i
     */
    private void showLoading(int i) {
        mErrorHintView.setVisibility(View.GONE);
        mListView.setVisibility(View.GONE);

        switch (i){
            case 1:
                mErrorHintView.hideLoading();
                mListView.setVisibility(View.VISIBLE);
                break;
            case 2:
                mErrorHintView.hideLoading();
                mErrorHintView.netError(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        defParams();
                        showLoading(VIEW_LOADING);
                        loadPhoneTechComments(true);
                    }
                });
                break;
            case 3:
                mErrorHintView.hideLoading();
                mErrorHintView.loadFailure(new ErrorHintView.OperateListener() {
                    @Override
                    public void operate() {
                        defParams();
                        showLoading(VIEW_LOADING);
                        loadPhoneTechComments(true);
                    }
                });
                break;
            case 4:
                mErrorHintView.loadingdata();
                break;
            case 5:
                mErrorHintView.hideLoading();
                mErrorHintView.noData();
                break;
        }
    }

    /**
     * 恢复默认参数
     */
    private void defParams() {
       offset = 0;
       isPage = true;
    }

    private void loadPhoneTechComments(final boolean flag) {
        RequestParams params = new RequestParams();
        String  t = String.valueOf(System.currentTimeMillis() / 1000); //获取当前时间
        params.put("timestamp", t);  //当前时间戳
        String token1 = MD5Utils.md5("d19cf361181f5a169c107872e1f5b722" + t);
        params.put("token1", token1);  //token1算法

        params.put("apiid", 3);
        params.put("module", "api_libraries_sjdbg_commentlist");
        params.put("avatar", "middle");
        params.put("docid", docid);
        params.put("returnformat", "json");
        params.put("encoding", "utf8");
//		params.put("onetime", timeStamp);			//分页用，传第一条新闻的时间戳，第一页下不用传值。
        params.put("offset", offset);   //分页用，数据记录的起始行数。0为第一条记录。
        params.put("rows", 10);  //分页用，数据记录每次取得的行数。不传此参数则默认获取10条记录。

        AsyncHttpUtil.get(Contacts.PHONE_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (footerView != null){
                    mListView.getRefreshableView().removeFooterView(footerView);
                    footerView = null;
                }

                mListView.onRefreshComplete();

                if (responseBody != null && responseBody.length > 0){
                    try {
                        JSONObject object = new JSONObject(new String(responseBody));
                        String status = object.getString("status");
                         if(TextUtils.equals("1", status)){
                            offset += 10;
                             JSONObject data = object.getJSONObject("data");
                             JSONArray  list = data.getJSONArray("result");
                             if (list != null){
                                 List<ArticleComment> instance = JsonUtils.getInstance(ArticleComment.class, list);
                                 if (instance != null && instance.size() > 0){
                                      if (flag){
                                          ArticleData.clear();
                                      }
                                     ArticleData.addAll(instance);
                                     if (ArticleData.size() == 0){
                                          showLoading(VIEW_NODATA);
                                     }else{
                                          showLoading(VIEW_LIST);
                                          mAdapter.notifyDataSetChanged();
                                     }
                                 }else{
                                     showLoading(VIEW_LOADFAILURE);
                                 }
                             }

                             JSONObject paging = data.getJSONObject("paging");
                             if (paging != null){
                                 PhonePaging instance = JsonUtils.getInstance(PhonePaging.class, paging);
                                 if (instance != null){
                                        try {
                                           int total = Integer.parseInt(instance.getTotal());
                                           if (offset >= total){
                                               isPage = false;
                                           }else{
                                               isPage = true;
                                           }
                                        }catch (Exception e){
                                            isPage = true;
                                        }
                                 }
                             }
                         }else{
                             showLoading(VIEW_LOADFAILURE);
                         }
                    }catch (Exception e){
                        showLoading(VIEW_LOADFAILURE);
                    }
                }else{
                    showLoading(VIEW_LOADFAILURE);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    showLoading(VIEW_LOADFAILURE);
            }
        });


    }

    @Override
    protected void obtainInfo() {

    }

    public class TechCommentAdapter extends BaseAdapter{

        private Context mContext;
        private List<ArticleComment>  list = new ArrayList<>();

        public TechCommentAdapter(List<ArticleComment>  data, Context context) {
               super();
               this.list = data;
               this.mContext = context;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null){
                convertView = View.inflate(mContext, R.layout.view_item_comment_lv, null);
                holder = new ViewHolder();
                holder.circleImageView = (CircleImageView)convertView.findViewById(R.id.comment_image);
                holder.name = (TextView)convertView.findViewById(R.id.comment_name);
                holder.time = (TextView)convertView.findViewById(R.id.comment_date);
                holder.content = (TextView)convertView.findViewById(R.id.comment_info);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            ArticleComment comment = list.get(position);
            if (!TextUtils.isEmpty(comment.getAvatar())){
                Picasso.with(mContext).load(comment.getAvatar()).placeholder(R.mipmap.touxiang).error(R.mipmap.touxing).into(holder.circleImageView);
            }
            holder.name.setText(comment.getUsername());
            holder.time.setText(comment.getDate());
            holder.content.setText(Html.fromHtml(comment.getContent()));
            return convertView;
        }

        public class ViewHolder{
            CircleImageView circleImageView;
            TextView  name;
            TextView  time;
            TextView  content;
        }
    }
}
